package com.fyl.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.util.Map;
import java.util.Properties;

@Configuration
@EnableConfigurationProperties(QuartzProperties.class)
public class QuartzConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(QuartzConfiguration.class);

//    @Bean
//    public SpringBeanJobFactory getSpringBeanJobFactory() {
//        return new SpringBeanJobFactory();
//    }

    private final QuartzProperties properties;

    public QuartzConfiguration(QuartzProperties properties) {
        this.properties = properties;
    }

    @Bean
    public SpringBeanJobFactory getSpringBeanJobFactory() {
        return new AutowiringSpringBeanJobFactory();
    }


    @Bean(name = "schedulerFactoryBean")
    public SchedulerFactoryBean createSchedulerFactoryBean(SpringBeanJobFactory springBeanJobFactory) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        schedulerFactoryBean.setJobFactory(springBeanJobFactory);

        if (this.properties.getSchedulerName() != null) {
            schedulerFactoryBean.setSchedulerName(this.properties.getSchedulerName());
        }
        schedulerFactoryBean.setAutoStartup(this.properties.isAutoStartup());
        schedulerFactoryBean.setStartupDelay((int) this.properties.getStartupDelay().getSeconds());
        schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown(this.properties.isWaitForJobsToCompleteOnShutdown());
        schedulerFactoryBean.setOverwriteExistingJobs(this.properties.isOverwriteExistingJobs());
        if (!this.properties.getProperties().isEmpty()) {
            schedulerFactoryBean.setQuartzProperties(asProperties(this.properties.getProperties()));
        }
        return schedulerFactoryBean;
    }

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }

    @Bean
    public QuartzManager quartzManager(SchedulerFactoryBean schedulerFactoryBean) {
        QuartzManager quartzManager = new QuartzManager(schedulerFactoryBean);
        logger.info("QuartzManager created");
        return quartzManager;
    }
}
